package com.prs.crm.action.crm;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.Constrains;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.crm.Customer;
import com.prs.crm.domain.crm.DocumenTary;
import com.prs.crm.domain.crm.DocumenTaryStyle;
import com.prs.crm.domain.crm.LiaisonWay;
import com.prs.crm.domain.crm.Linkman;
import com.prs.crm.exception.InValidDeleteException;
import com.prs.crm.service.crm.CustomerAppointService;
import com.prs.crm.service.crm.DocumenTaryService;
import com.prs.crm.service.crm.DocumenTaryStyleService;
import com.prs.crm.service.crm.LinkmanService;

public class LinkmanAction extends BaseAction{
	
	private static final long serialVersionUID = 1L;
	
	private Linkman linkman;
	private Customer customer;
	private DocumenTary documenTary;
	private LinkmanService linkmanService;
	private PaginationSupport pagination;
	private Integer[] linkmanIds;
	
	private CustomerAppointService customerAppointService;
	private DocumenTaryService documenTaryService;
	
	private File upload;
	private String uploadFileName;
	private String tradeIds;
	private List<DocumenTary> tarys;
	private List<DocumenTaryStyle> styles;
	private DocumenTaryStyleService documenTaryStyleService;
	
	@Action("listLinkman")
	public String execute() {
		return SUCCESS;
	}
	@Action("listLinkmanOA")
	public String listOA() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(Linkman.class);
		//criteria.add(Restrictions.isNotNull("customer"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getLinkmanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	@Action("editDocumenTary3")
	public String editDocumenTary3() {
		if(linkmanIds!=null){
			this.linkman=this.linkmanService.get(linkmanIds[0]);
		}
		this.styles=this.documenTaryStyleService.getAllStyles();
		return SUCCESS;
	}
	@Action(value="saveDocumenTary3",results={
			@Result(name="success",type="redirect",location="listLinkmanOA"),
			@Result(name="error",type="chain",location="editLinkman")})
	public String saveDocumenTary3() {	
		this.documenTary.setLinkman1(linkman);
		this.documenTaryService.save(documenTary);
		this.setPrompt("创建跟单成功");
		return SUCCESS;
	}
	@Action(value="saveDocT3",results={
			@Result(name="success",type="redirect",location="viewLinkman?linkman=${linkman.getId()}"),
			@Result(name="error",type="chain",location="editLinkman")})
	public String saveDocT3() {	
		this.documenTary.setLinkman1(linkman);
		this.documenTaryService.save(documenTary);
		this.setPrompt("创建跟单成功");
		return SUCCESS;
	}
	@Action("listLinkmanByTrade")
	public String listLinkmanByTrade(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(Linkman.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		if(tradeIds != null){
			if(!"all".equals(tradeIds)){
				tradeIds = tradeIds.split(",")[0];
				if(ToolKits.isInteger(tradeIds)){
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.trade", "tr");
					criteria.add(Restrictions.eq("tr.id", Integer.parseInt(tradeIds)));
				}
			}
		}
		this.setPagination(this.getLinkmanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	@Action("selectInCustomer")
	public String selectQuoCustomer() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Customer.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getLinkmanService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	@Action("listBirthdayLinkman")
	public String listBirthdayLinkman() {
		pagination = this.getPaginationHelper().prepare(pagination);
		
		Collection<Linkman> linkmans = this.getLinkmanService().getTodayBirthdayLinkman();
		List<Linkman> results = new ArrayList<Linkman>();
		for(Linkman linkman : linkmans) {
			results.add(linkman);
		}
		pagination.setItems(results);
		pagination.setTotalCount(results.size());
		int totalPage = pagination.getTotalCount() / pagination.getPageSize();
        if(totalPage * pagination.getPageSize() < pagination.getTotalCount())
              totalPage++;
        pagination.setTotalPage(totalPage);
		return SUCCESS;
	}
	
	@Action("listBirthdayLinkman4Appoint")
	public String listTodayBirthdayLinkman4Appoint() {
		pagination = this.getPaginationHelper().prepare(pagination);
		Collection<Linkman> linkmans = this.getCustomerAppointService().getTodayBirthdayLinkman4Appoint(AppContext.getAccountContext().currentUser());
		List<Linkman> results = new ArrayList<Linkman>();
		
		for(Linkman linkman : linkmans) {
			results.add(linkman);
		}
		pagination.setItems(results);
		pagination.setTotalCount(results.size());
		int totalPage = pagination.getTotalCount() / pagination.getPageSize();
        if(totalPage * pagination.getPageSize() < pagination.getTotalCount())
              totalPage++;
        pagination.setTotalPage(totalPage);		
		return SUCCESS;
	}
	
	@Action("editLinkman")
	public String edit() {
		if(linkmanIds!=null){
		this.linkman=this.linkmanService.get(linkmanIds[0]);
		}
		return SUCCESS;
	}
	@Action(value="removeLink",results={
			@Result(name="success",type="redirect",location="listLinkmanOA"),
			@Result(name="error",type="chain",location="editLinkman")})
	public String removeLink() {	
		this.linkmanService.batchRemove(linkmanIds);
		return SUCCESS;
	}
	
	@Action("viewLinkman")
	public String view() {
		if(linkmanIds!=null){
			this.linkman=this.linkmanService.get(linkmanIds[0]);
		}
		this.tarys=this.documenTaryService.getDocumenTaryByLinkman(linkman);
		return SUCCESS;
	}
	
	@Action("alterLinkman")
	public String alter() {
		return SUCCESS;
	}
	@Action("alterLinkmanByTrade")
	public String alterLinkmanByTrade(){
		return this.listLinkmanByTrade();
	}
	@Action(value="saveLinkman2",results={
			@Result(name="success",type="redirect",location="listCustomerOA"),
			@Result(name="error",type="chain",location="editLinkman2")})
	public String save2() {
		linkman.setCustomer(customer);
		this.getLinkmanService().save(linkman);
		this.setPrompt("添加联系人成功");
		return SUCCESS;
	}
	@Action(value="saveLin",results={
			@Result(name="success",type="redirect",location="viewCustomer?customer=${customer.getId()}"),
			@Result(name="error",type="chain",location="editLinkman2")})
	public String saveLin() {
		
		linkman.setCustomer(customer);
		this.getLinkmanService().save(linkman);
		this.setPrompt("添加联系人成功");
		return SUCCESS;
	}
	@Clew(results={"success","none"})
	@Action(value="saveLinkman",results={
			@Result(name="success",type="redirect",location="listLinkmanOA"),
			@Result(name="none",type="redirect",location="listLinkmanOA"),
			@Result(name="error",type="chain",location="editLinkman")})
	public String save() {
//		if(linkman.getCustomer()==null||"".equals(linkman.getCustomer().getName().trim())){
//			this.addActionError("请选择客户");
//			return ERROR;
//		}
//		if(linkman.getName()==null||"".equals(linkman.getName().trim())){
//			this.addActionError("请输入联系人姓名");
//			return ERROR;
//		}
//		if (isnull(linkman.getMobileNo1())) {
//			if (!ToolKits.isInteger(linkman.getMobileNo1())) {
//				this.addActionError("手机号码1只能由数字组成!请重新输入");
//				return ERROR;
//			}
//		}
//		if (isnull(linkman.getMobileNo2())) {
//			if (!ToolKits.isInteger(linkman.getMobileNo2())) {
//				this.addActionError("手机号码2只能由数字组成!请重新输入");
//				return ERROR;
//			}
//		}
//		
//		if ( !"".equals(linkman.getOfficePhone().trim())
//				&&!ToolKits.isInteger(linkman.getOfficePhone())) {
//			this.addActionError("办公电话只能为数字类型");
//			return ERROR;
//		}
//		
//		if ( !"".equals(linkman.getFax().trim())
//				&&!ToolKits.isInteger(linkman.getFax())) {
//			this.addActionError("传真只能为数字类型");
//			return ERROR;
//		}
//		if ( !"".equals(linkman.getQQ_No().trim())
//				&&!ToolKits.isInteger(linkman.getQQ_No())) {
//			this.addActionError("QQ只能为数字类型");
//			return ERROR;
//		}
//		if (!"".equals(linkman.getPostcode().trim())
//				&& !ToolKits.isInteger(linkman.getPostcode())) {
//			this.addActionError("邮编只能为数字");
//			return ERROR;
//		}
//		
//		
//		String emailString = "\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+";// "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+ ([-.]\\w+)*";
//
//		Pattern p = Pattern.compile(emailString);
//		Matcher m = p.matcher(linkman.getEmail().trim());
//		boolean b = m.matches();
//		if (!"".equals(linkman.getEmail().trim())&&!b) {
//			addActionError("电子邮件格式不正确");
//			return ERROR;
//		}
//		
//		if (!"".equals(linkman.getStature().trim())
//				&& !ToolKits.isInteger(linkman.getStature())) {
//			this.addActionError("身高只能为数字类型");
//			return ERROR;
//		}
//		if (!"".equals(linkman.getWeight().trim())
//				&& !ToolKits.isNumeric(linkman.getWeight())) {
//			this.addActionError("体重只能为数字类型");
//			return ERROR;
//		}
//		if (!"".equals(linkman.getShoes().trim())
//				&& !ToolKits.isNumeric(linkman.getShoes())) {
//			this.addActionError("鞋码只能为数字类型");
//			return ERROR;
//		}
		if(linkman.getId() == null) {
			this.setPrompt("提交联系人成功");
			linkman.setCustomer(customer);
			linkman.setState(Constrains.TASK_AUDITING);
			this.getLinkmanService().saveLinkmans(linkman, upload, uploadFileName);
			return SUCCESS;
		}else {
			this.setPrompt("修改联系人成功");
			//this.getLinkmanService().save(linkman);
			this.getLinkmanService().saveLinkmans(linkman, upload, uploadFileName);
			return NONE;
		}

		
	}
	
	@Action(value="removeLinkman",results={
			@Result(name="success",type="redirect",location="listLinkmanOA"),
			@Result(name="error",type="chain",location="listLinkmanOA")})
	public String remove() {
		for(int i=0;i<linkmanIds.length;i++){
			Linkman lin=this.linkmanService.get(linkmanIds[i]);
			//查询联系人关联跟单
			List<DocumenTary> docs=this.documenTaryService.getDocumenTaryByLinkman(lin);
			if(docs!=null){
				for(DocumenTary doc:docs){
					this.documenTaryService.remove(doc);
				}
			}
			this.linkmanService.remove(lin);
		}
		return SUCCESS;
	}
	
	public Linkman getLinkman() {
		return linkman;
	}
	public void setLinkman(Linkman linkman) {
		this.linkman = linkman;
	}
	
	public Customer getCustomer() {
		return customer;
	}
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}
	public LinkmanService getLinkmanService() {
		return linkmanService;
	}
	public void setLinkmanService(LinkmanService linkmanService) {
		this.linkmanService = linkmanService;
	}
	public PaginationSupport getPagination() {
		return pagination;
	}
	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}
	public Integer[] getLinkmanIds() {
		return linkmanIds;
	}
	public void setLinkmanIds(Integer[] linkmanIds) {
		this.linkmanIds = linkmanIds;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public void setCustomerAppointService(CustomerAppointService customerAppointService) {
		this.customerAppointService = customerAppointService;
	}
	public CustomerAppointService getCustomerAppointService() {
		return customerAppointService;
	}
	public String getTradeIds() {
		return tradeIds;
	}
	public void setTradeIds(String tradeIds) {
		this.tradeIds = tradeIds;
	}	
	
	public boolean isphone(String str) {
		str=str.trim();
		boolean tag = false;
		final String pattern ="[1]{1}[3,5,8,6]{1}[0-9]{9}";
		final Pattern patt = Pattern.compile(pattern);
		final Matcher mat2 = patt.matcher(str);
		if (!mat2.find()) {
			tag = true;
		}
		return tag;
	}

	public boolean isnull(String str) {
		boolean s = true;
		if (str == null||str.trim().equals("") ) {
			s = false;
		}
		return s;
	}
	public DocumenTary getDocumenTary() {
		return documenTary;
	}
	public void setDocumenTary(DocumenTary documenTary) {
		this.documenTary = documenTary;
	}
	public DocumenTaryService getDocumenTaryService() {
		return documenTaryService;
	}
	public void setDocumenTaryService(DocumenTaryService documenTaryService) {
		this.documenTaryService = documenTaryService;
	}
	public List<DocumenTary> getTarys() {
		return tarys;
	}
	public void setTarys(List<DocumenTary> tarys) {
		this.tarys = tarys;
	}
	public List<DocumenTaryStyle> getStyles() {
		return styles;
	}
	public void setStyles(List<DocumenTaryStyle> styles) {
		this.styles = styles;
	}
	public DocumenTaryStyleService getDocumenTaryStyleService() {
		return documenTaryStyleService;
	}
	public void setDocumenTaryStyleService(
			DocumenTaryStyleService documenTaryStyleService) {
		this.documenTaryStyleService = documenTaryStyleService;
	}
	
}
